package org.focusj.scala.io

import java.io.PrintWriter
import scala.util.Random
import org.focusj.randtext.RandCharacters._
import scala.io.Source
import java.io.File
import scala.collection._

object LogFile {
    def nextIp = Random.nextInt(255) + "." + Random.nextInt(255) + "." + Random.nextInt(255)
    def nextUri = "/" + Random.nextEns(5).mkString + "/" + Random.nextEns(5).mkString
    lazy val lines = getLines

    /**
     * 写入测试文件
     */
    def writeFile() = {
        val out = new PrintWriter("D:\\test.log")
        for (i <- 0 to 1000) {
            out.println(System.currentTimeMillis() + " " + nextIp + " " + nextUri)
        }
        out.close()
    }

    def getLines = {
        Source.fromFile(new File("D:\\test.log")).getLines().map(line => {
            line.split(" ")
        })
    }

    /**
     * 一份日志文件中url的访问数
     */
    def byUrl() = {
        ((Map[String, Int]()) /: lines)((r, m) => r + (m(2) -> { r.getOrElse(m(2), 0) + 1 }))
    }

    /**
     * 人均
     */
    def byId() = {
        ((Map[String, Int]()) /: lines)((r, m) => r + (m(0) -> { r.getOrElse(m(0), 0) + 1 }))
    }

    def main(args: Array[String]) {
        byUrl foreach println _
    }
}